package com.zjd.controller.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.zjd.domain.Route;
import com.zjd.service.RouteService;
import com.zjd.service.impl.RouteServiceImpl;
import com.zjd.utils.BaseServlet;
import org.apache.ibatis.annotations.Insert;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/RouteServlet")
public class RouteServlet extends BaseServlet {
    private RouteService service = new RouteServiceImpl();

    public void udpateRoute() throws IOException {
        System.out.println("fhdskla");
        ServletInputStream inputStream = request.getInputStream();
        Route route = new ObjectMapper().readValue(inputStream, Route.class);
        System.out.println(route);
        service.updateRoute(route);
        response.getWriter().write("ok");
    }

    public void findRouteByid() throws IOException, ServletException {
        ServletInputStream inputStream = request.getInputStream();
        Route route = new ObjectMapper().readValue(inputStream, Route.class);
        Route editRoute = service.findRouteByid(route);
        System.out.println(editRoute);
        writeJson(response,editRoute);
    }

    public void saveRoute() throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        Route route = new ObjectMapper().readValue(inputStream, Route.class);
        service.saveRoute(route);
        response.getWriter().write("ok");
    }

    public void delReoute() throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        Route route = new ObjectMapper().readValue(inputStream, Route.class);
        service.delReoute(route);
        response.getWriter().write("ok");
    }

    public void selectRoutesByPage() throws ServletException, IOException {
        String spageNum = request.getParameter("pageNum");
        String spageSize = request.getParameter("pageSize");
        int pageNum = 1;
        int pageSize = 5;
        if (spageNum != "" && spageNum != null && spageNum != "0") {
            pageNum = Integer.valueOf(spageNum);
        }
        if (spageSize != "" && spageSize != null && spageSize != "0") {
            pageSize = Integer.valueOf(spageSize);
        }

        PageInfo<Route> pageInfo = service.selectRoutesByPage(pageNum, pageSize);
        //System.out.println(pageInfo);
        writeJson(response, pageInfo);
    }

}